package com.xu.cloud.common.process.support;

import com.xu.cloud.common.api.XuApiMethod;
import com.xu.cloud.common.process.IProcessSelector;
import com.xu.cloud.common.process.IProcessor;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 根据 {@link XuApiMethod} 注解解析的业务执行选择器
 *
 * @author xuguan
 * @since 2025/1/17
 * @see XuApiMethod
 */
public class XuApiMethodAnnotatedProcessSelector implements IProcessSelector, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public IProcessor select(Method method) {
        final XuApiMethod xuApiMethod = AnnotatedElementUtils.findMergedAnnotation(method, XuApiMethod.class);
        if (Objects.isNull(xuApiMethod) || !StringUtils.hasText(xuApiMethod.processorBeanName())) {
            return new NopProcessor();
        }
        return applicationContext.getBean(xuApiMethod.processorBeanName(), IProcessor.class);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
